#include "TrackActor.h"
#include "Track.h"
#include "JetActor.h"
TrackActor::TrackActor(Ogre::SceneManager *scene,Track *track)
{
    m_track = NULL;
    m_scene = NULL;
    m_node = NULL;
    m_entity = NULL;

    m_track = track;
    m_scene  = scene;
    m_type = ActorType(TRACK);
    build_track();

}

void TrackActor::build_track()
{

    m_manualObject = NULL;
    std::vector<TrackVector>::iterator it;

    Ogre::String name = m_track->GetName();
    m_manualObject = m_scene->createManualObject(name);
    m_manualObject->setDynamic(false);



    m_manualObject->begin("debug",Ogre::RenderOperation::OT_TRIANGLE_LIST);

    long vertex_counter = 0;

    float distance_counter = 0;
    for(it = m_track->GetVectorList().begin(); it < m_track->GetVectorList().end(); it++)
    {

        m_manualObject->position((*it).GetPosition() - (*it).GetCurvature()/2);
        m_manualObject->textureCoord(0,distance_counter);

        m_manualObject->position((*it).GetPosition() + (*it).GetCurvature()/2);
        m_manualObject->textureCoord((*it).GetSize()/10,distance_counter);

        distance_counter += (*it).GetDirector().length()/10;
        if(distance_counter > 1)
            distance_counter = 0;

        m_manualObject->position((*it).GetPosition() + (*it).GetDirector() - (*it).GetCurvature()/2);
        m_manualObject->textureCoord(0,distance_counter);

        m_manualObject->position((*it).GetPosition() + (*it).GetDirector() + (*it).GetCurvature()/2);
        m_manualObject->textureCoord((*it).GetSize()/10,distance_counter);

        TrackVector *temp_vector;
        if(&(*it) == &m_track->GetVectorList().back())
            temp_vector = &m_track->GetVectorList().front();
        else
            temp_vector = &(*(it+1));

        distance_counter += (temp_vector->GetPosition() - (*it).GetPosition()).length()/10;
        if(distance_counter > 1)
            distance_counter = 0;

        m_manualObject->position(temp_vector->GetPosition() - temp_vector->GetCurvature()/2);
        m_manualObject->textureCoord(0,distance_counter);

        m_manualObject->position(temp_vector->GetPosition()  + temp_vector->GetCurvature()/2);
        m_manualObject->textureCoord((*it).GetSize()/10,distance_counter);

        m_manualObject->triangle(vertex_counter,vertex_counter+1,vertex_counter+2);
        m_manualObject->triangle(vertex_counter+1,vertex_counter+2,vertex_counter+3);
        m_manualObject->triangle(vertex_counter+2,vertex_counter+3,vertex_counter+4);
        m_manualObject->triangle(vertex_counter+3,vertex_counter+4,vertex_counter+5);

        vertex_counter += 6;
    }
    m_manualObject->end();


    m_trackMeshName = name + "_mesh";
    m_manualObject->convertToMesh(m_trackMeshName);

    m_entity = m_scene->createEntity(m_trackMeshName);

    m_node = m_scene->getRootSceneNode()->createChildSceneNode();
    m_node->attachObject(m_entity);


}

